package com.pet.platform.service.impl;

import com.pet.platform.exception.BusinessException;
import com.pet.platform.common.Constants;
import com.pet.platform.common.PageResult;
import com.pet.platform.dto.PostDTO;
import com.pet.platform.dto.PostQueryDTO;
import com.pet.platform.entity.Post;
import com.pet.platform.entity.User;
import com.pet.platform.mapper.PostMapper;
import com.pet.platform.service.PostService;
import com.pet.platform.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class PostServiceImpl implements PostService {

    @Autowired
    private PostMapper postMapper;

    @Autowired
    private UserService userService;

    @Override
    public Post findById(Long id) {
        return postMapper.findById(id);
    }

    @Override
    public PageResult<PostDTO> findPage(PostQueryDTO queryDTO) {
        Map<String, Object> params = new HashMap<>();
        params.put("title", queryDTO.getTitle());
        params.put("content", queryDTO.getContent());
        params.put("userId", queryDTO.getUserId());
        params.put("status", queryDTO.getStatus());
        params.put("offset", queryDTO.getOffset());
        params.put("pageSize", queryDTO.getPageSize());
        params.put("orderBy", queryDTO.getOrderBy());
        params.put("isAsc", queryDTO.getIsAsc());

        List<Post> posts = postMapper.findList(params);
        Long total = postMapper.count(params);

        List<PostDTO> postDTOs = posts.stream().map(post -> {
            PostDTO dto = new PostDTO();
            BeanUtils.copyProperties(post, dto);
            User user = post.getUser();
            if (user != null) {
                dto.setUsername(user.getUsername());
                dto.setUserAvatar(user.getAvatar());
            }
            return dto;
        }).collect(Collectors.toList());

        return new PageResult<>(postDTOs, total, queryDTO.getPageNum(), queryDTO.getPageSize());
    }

    @Override
    @Transactional
    public void create(PostDTO postDTO) {
        User currentUser = userService.getCurrentUser();
        
        Post post = new Post();
        BeanUtils.copyProperties(postDTO, post);
        post.setUserId(currentUser.getId());
        post.setStatus(Constants.STATUS_NORMAL);
        post.setLikes(0);
        post.setComments(0);
        
        postMapper.insert(post);
    }

    @Override
    @Transactional
    public void update(Long id, PostDTO postDTO) {
        Post post = findById(id);
        if (post == null) {
            throw new BusinessException("帖子不存在");
        }

        User currentUser = userService.getCurrentUser();
        if (!currentUser.getId().equals(post.getUserId()) && !Constants.ROLE_ADMIN.equals(currentUser.getRole())) {
            throw new BusinessException("没有权限修改此帖子");
        }

        BeanUtils.copyProperties(postDTO, post);
        post.setId(id);
        post.setUserId(post.getUserId());  // 保持原作者不变
        postMapper.update(post);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        Post post = findById(id);
        if (post == null) {
            throw new BusinessException("帖子不存在");
        }

        User currentUser = userService.getCurrentUser();
        if (!currentUser.getId().equals(post.getUserId()) && !Constants.ROLE_ADMIN.equals(currentUser.getRole())) {
            throw new BusinessException("没有权限删除此帖子");
        }

        postMapper.delete(id);
    }

    @Override
    @Transactional
    public void like(Long id) {
        Post post = findById(id);
        if (post == null) {
            throw new BusinessException("帖子不存在");
        }
        postMapper.updateLikes(id, true);
    }

    @Override
    @Transactional
    public void unlike(Long id) {
        Post post = findById(id);
        if (post == null) {
            throw new BusinessException("帖子不存在");
        }
        postMapper.updateLikes(id, false);
    }
} 